package com.gitee.linzl.zuul.gateway.fiters.pre;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.gitee.linzl.zuul.gateway.fiters.AbstractDefaultPreFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import lombok.extern.slf4j.Slf4j;

/**
 * 判断是否有token值,及其有效性、权限鉴定
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年10月1日
 */
@Component
@Slf4j
public class AuthTokenFilter extends AbstractDefaultPreFilter {
	private static String TOKEN_NAME = "token";
	public static String HEADER_TOKEN_NAME = "Authorization";

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		String uri = request.getRequestURI();// 忽略部分请求验证
		if ("/favicon.ico".equals(uri)) {
			return null;
		}

		// 从url中获取
		String token = request.getParameter(TOKEN_NAME);

		if (StringUtils.isEmpty(token)) {
			// 从header获取
			token = request.getHeader(HEADER_TOKEN_NAME);
			if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
				token = token.substring(7);
			}
		}

		// 从cookie获取
		if (StringUtils.isEmpty(token)) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (TOKEN_NAME.equalsIgnoreCase(cookie.getName())) {
						token = cookie.getValue();
					}
				}
			}
		}

		if (StringUtils.isNotEmpty(token)) {
			// 检测TOKEN有效性
			log.debug("得到token值{}", token);

			// 解密Token,得到用户信息,并鉴定用户访问权限
			// TODO

			ctx.put("userId", "解析Token得到用户ID等信息");

			// 将token统一放入header
			ctx.addZuulRequestHeader(TOKEN_NAME, token);
		} else {
			JSONObject error = new JSONObject();
			error.put("errCode", "1000");
			error.put("errMsg", "token无效");
			setFailedResponse(error.toString(), 200);
		}
		return null;
	}

}
